package com.wuxiaoge.job;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.job.builder.FlowBuilder;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.job.flow.Flow;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.support.JdbcTransactionManager;
import org.springframework.stereotype.Component;

@Component
public class FlowJobDemo {


    @Bean
    public Job flowJob(JobRepository jobRepository, JdbcTransactionManager transactionManager) {
        return new JobBuilder("flowJob3", jobRepository)
                .start(flow(jobRepository,transactionManager))
                .next(step3(jobRepository,transactionManager))
                .end()
                .build();

    }

    private Step step1(JobRepository jobRepository, JdbcTransactionManager transactionManager) {

        return new StepBuilder("step1", jobRepository)
                .tasklet((contribution, chunkContext) -> {
                    System.out.println(Thread.currentThread().getName()+"执行步骤一操作。。。");
                    return RepeatStatus.FINISHED;
                },transactionManager).build();
    }

    private Step step2(JobRepository jobRepository, JdbcTransactionManager transactionManager) {
        return new StepBuilder("step2", jobRepository)
                .tasklet((contribution, chunkContext) -> {
                    System.out.println(Thread.currentThread().getName()+"执行步骤二操作。。。");
                    return RepeatStatus.FINISHED;
                },transactionManager).build();
    }

    private Step step3(JobRepository jobRepository, JdbcTransactionManager transactionManager) {

        return new StepBuilder("step3", jobRepository)
                .tasklet((contribution, chunkContext) -> {
                    System.out.println(Thread.currentThread().getName()+"执行步骤三操作。。。");
                    return RepeatStatus.FINISHED;
                },transactionManager).build();
    }

    // 创建一个flow对象，包含若干个step
    private Flow flow(JobRepository jobRepository, JdbcTransactionManager transactionManager) {
        return new FlowBuilder<Flow>("flow")
                .start(step1(jobRepository,transactionManager))
                .next(step2(jobRepository,transactionManager))
                .build();
    }
}